class Node(object):
    __slots__ = ("position", "neighbours")
    
    def __init__(self, position):
        self.position = position
        self.neighbours = set()
    
    def link(self, node):
        self.neighbours.add(node)
        node.neighbours.add(self)
    
    def unlink(self, node):
        self.neighbours.remove(node)
        node.neighbours.remove(self)
    
    def __str__(self):
        return str(self.position)

class Graph(object):
    def __init__(self, nodes):
        self.nodes = nodes
    
    def remove(self, node):
        for neighbour in set(node.neighbours):
            node.unlink(neighbour)
        
        self.nodes.remove(node)
    
    def trim(self, keep):
        new = set((keep,))
        found = set()
        
        while new - found:
            for node in set(new):
                new |= node.neighbours
                found.add(node)
        
        for node in self.nodes - found:
            self.remove(node)
